package com.amtf.datafile2.core.txt;

import com.amtf.datafile2.DataException;
import com.amtf.datafile2.cfg.txt.TxtDataFieldDefinition;
import com.amtf.datafile2.core.std.StdDataField;

public class TxtDataField extends StdDataField<TxtDataFieldDefinition> {

	public TxtDataField(TxtDataFieldDefinition def) {
		super(def);
	}

	@Override
	public void setValue(String value) {
		if (value == null) {
			this.value = "";
		} else {
			if (definition.getQuote() != ' ' && value.length() != 0) {
				// value = value.trim();
				if (value.charAt(0) == definition.getQuote() && value.charAt(value.length() - 1) == definition.getQuote()) {
					value = value.substring(1, value.length() - 1);
				}
			}
			if (definition.isTrimValue()) {
				this.value = value.trim();
			} else {
				this.value = value;
			}
		}
	}

	public void validate() {
		if (definition.isCheckFormat()) {
			this.clearErrors();
			if (!definition.isAllowEmpty() && value.length() == 0) {
				this.appendError("Empty value is not allowed.");
			}

			try {
				definition.getType().validate(this);
			} catch (DataException e) {
				this.appendError(e.getMessage());
			}
		}
	}

	public String toString(char delimiter) {
		String tmpValue = definition.getFormat().format(this);

		char quote = definition.getQuote();
		if (quote != ' ') {
			if (definition.isForceQuote()) {
				tmpValue = quote + tmpValue + quote;
			} else if (tmpValue.indexOf(delimiter) != -1) {
				tmpValue = quote + tmpValue + quote;
			}
		}

		return tmpValue;
	}

	@Override
	public String toString() {
		char demiliter = definition.getDataRecordDefinition().getFieldDelimiter();
		return toString(demiliter);
	}

	// public static String toString(DataField field, TxtDataFieldDefinition definition) {
	// char delimiter = definition.getDataRecordDefinition().getFieldDelimiter();
	// String tmpValue = definition.getPadType().pad(field);
	//
	// char quote = definition.getQuote();
	// if (quote != ' ') {
	// if (definition.isForceQuote()) {
	// tmpValue = quote + tmpValue + quote;
	// } else if (tmpValue.indexOf(delimiter) != -1) {
	// tmpValue = quote + tmpValue + quote;
	// }
	// }
	//
	// return tmpValue;
	// }

}
